<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin\Sys;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Model\Menu;
use App\Model\RoleMenu;
use Hyperf\DbConnection\Db;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;

#[Middlewares([AuthMiddleware::class])]
#[Controller]
class MenuController extends AbstractController
{
    #[GetMapping(path: '/sys/menu/routers')]
    public function routers()
    {
        $menus = Menu::query()->select('id', 'parent_id as parentId', 'path', 'type', 'component', 'title', 'sort', 'icon', 'redirect', 'name', 'hidden', 'is_external as isExternal')
            ->where('hidden', 0)
            ->orderBy('sort') // 按排序字段排序
            ->get();
        // 获取菜单数结构的数据
        $indexedElements = [];
        $tree = [];
        // 创建索引数组以便快速查找
        foreach ($menus->toArray() as $element) {
            $indexedElements[$element['id']] = $element;
            $indexedElements[$element['id']]['meta'] = [
                'title' => $element['title'],
                'icon' => $element['icon'],
                'hidden' => $element['hidden'],
                'isExternal' => $element['isExternal'],
            ];
            $indexedElements[$element['id']]['children'] = [];
        }

        foreach ($indexedElements as &$element) {
            if ($element['parentId'] == 0) {
                $tree[] = &$element;
            } else {
                if (isset($indexedElements[$element['parentId']])) {
                    $indexedElements[$element['parentId']]['children'][] = &$element;
                }
            }
        }
        return success($tree);
    }

    #[GetMapping(path: '/sys/menu/tree')]
    public function tree()
    {
        $menus = Menu::query()->select('id', 'parent_id as parentId', 'path', 'type', 'component', 'title', 'sort', 'icon', 'redirect', 'name', 'hidden', 'is_external as isExternal')
            ->orderBy('sort') // 按排序字段排序
            ->get();
        // 获取菜单数结构的数据
        $indexedElements = [];
        $tree = [];
        // 创建索引数组以便快速查找
        foreach ($menus->toArray() as $element) {
            $indexedElements[$element['id']] = $element;
            $indexedElements[$element['id']]['children'] = [];
        }

        foreach ($indexedElements as &$element) {
            if ($element['parentId'] == 0) {
                $tree[] = &$element;
            } else {
                if (isset($indexedElements[$element['parentId']])) {
                    $indexedElements[$element['parentId']]['children'][] = &$element;
                }
            }
        }
        return success($tree);
    }

    #[RequestMapping(path: '/sys/menu', methods: ['POST', 'PUT'])]
    public function menu()
    {
        $params = $this->request->all();
        if (isset($params['id'])) {
            Menu::query()->where('id', $params['id'])->update([
                'parent_id' => $params['parentId'],
                'path' => $params['path'],
                'type' => $params['type'],
                'component' => $params['component'],
                'title' => $params['title'],
                'sort' => $params['sort'],
                'icon' => $params['icon'],
                'redirect' => $params['redirect'],
                'name' => $params['name'],
                'hidden' => $params['hidden'],
                'is_external' => $params['isExternal'],
                'perm' => $params['perm']
            ]);
        } else {

            Menu::query()->create([
                'parent_id' => $params['parentId'],
                'path' => $params['path'],
                'type' => $params['type'],
                'component' => $params['component'],
                'title' => $params['title'],
                'sort' => $params['sort'],
                'icon' => $params['icon'],
                'redirect' => $params['redirect'],
                'name' => $params['name'],
                'hidden' => $params['hidden'],
                'is_external' => $params['isExternal'],
                'perm' => $params['perm']
            ]);
        }
        return success();

    }

    #[DeleteMapping(path: '/sys/menu/delete/{id}')]
    public function delete($id)
    {
        try {
            Db::beginTransaction();
            Menu::query()->where('id', $id)->delete();
            RoleMenu::query()->where('menu_id', $id)->delete();
            return success();
        } catch (\Throwable $e) {
            logInfo('delete', $e->getMessage(), 'menu');
        }

    }
}
